#!/usr/bin/env python
#coding:utf-8
#linux上运行
#python基础教程第二版的poll异步IO示例程序，稍微加了几句代码以便于观察程序运行情况。
#可以用socket_testclient.py程序作为客户端来测试，根据输出信息观察程序运行过程。
#socket_testclient.py中改一下sendnumbers=5和testthreadnumbers=2就可以便于用小数据量来观察了。

import socket, select
import time

s = socket.socket()

#host = socket.gethostname()
host='192.168.171.128'
port = 12345
s.bind((host, port))

fdmap = {s.fileno(): s}

s.listen(5)
p = select.poll()
p.register(s)
while True:
    events = p.poll()
    for fd, event in events:
        for key,value in fdmap.items():
            print key,':',value
        print 'fd:',fd
        if fdmap[fd] is s:
            c, addr = s.accept()
            print 'Got connection from', addr
            p.register(c)
            fdmap[c.fileno()] = c
        elif event & select.POLLIN:
            data = fdmap[fd].recv(1024)
            if not data: # No data -- connection closed
                print fdmap[fd].getpeername(), 'disconnected'
                p.unregister(fd)
                del fdmap[fd]
            else:
                print fd,data
        time.sleep(0.5)
